package br.com.dispositivosmoveis.acompanhamentodeconta.abstracts;

import br.com.dispositivosmoveis.acompanhamentodeconta.util.GenericsReader;


public abstract class  CrudService<E,R extends AbstractRepository<E>> implements AbstractService<E>  {
	private R repository;
	private Class<R> repositoryClass;

	public R getRepository() {
		if(this.repository == null){
			this.repository = this.newInstance();
		}
		return repository;
	}

	private R newInstance() {
		try {
			return this.getRepositoryClass().newInstance();
		} catch (final Exception e) {
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	private Class<R> getRepositoryClass() {
		if (this.repositoryClass == null) {
			this.repositoryClass = (Class<R>) GenericsReader.getTypeArgument(
					this.getClass(), 1);
		}
		return this.repositoryClass;
	}


}
